<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before='true'>
        <!-- 左侧显示总记录数 -->
        <span slot="before">共{{page.total}}条记录</span>
        <!-- 右侧显示按钮 excel导入 excel导出 新增员工 -->
        <template v-slot:after>
          <el-button size="small" type="warning" @click="$router.push('/import')">excel导入</el-button>
          <el-button size="small" type="danger" @click="exportData">excel导出</el-button>
          <el-button size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </PageTools>

      <!-- 放置表格和分页               sortable是可排序的意思,就是会多一个上下的小箭头用来排序 -->  
      <el-card>
        <el-table border v-loading="loading" :data="list">                  
          <el-table-column type='index' label="序号" sortable="" />  
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column prop="mobile" label="手机号" sortable="" />
          <el-table-column>
            <!-- 插槽 -->
            <template slot-scope="{ row }">
              <img 
              @click="showQrCode(row.staffPhoto)" 
              v-imagerror="require('@/assets/common/bigUserHeader.png')" 
              :src="row.staffPhoto" 
              style="border-radius: 50%; width: 100px; height: 100px; padding: 10px">
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column :formatter="formatEmployment" prop="formOfEmployment" label="聘用形式" sortable="" />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable="" >
            <template slot-scope="{ row }">
              {{
                row.timeOfEntry | formatDate
              }}
            </template>
          </el-table-column>
          <el-table-column prop="enableState" label="账户状态" sortable="" >
            <template slot-scope="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{row}"> 
              <el-button :disabled="!checkPermission('aa')" type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="deleteEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件     用一个行布局组件包裹分页组件-->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination 
          :current-page="page.page" 
          :page-size="page.size"
          :total="page.total"
          @current-change='changePage'
          layout="prev, pager, next" 
          />
        </el-row>
      </el-card>
    </div>
    <!-- 放置弹层组件 -->
    <AddEmployee :showDialog.sync="showDialog"></AddEmployee>

     <!-- 二维码弹层 -->
    <el-dialog title="二维码" :visible.sync='showCodeDialog'>
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas"></canvas>
      </el-row>
    </el-dialog>

<!-- 放置分配角色弹层 -->
    <AssignRole ref="assignRole" :show-role-dialog.sync='showRoleDialog' :user-id="userId"></AssignRole>




  </div>
</template>

<script>
import AssignRole from './components/assign-role.vue'
import AddEmployee from "@/views/employees/components/add-employee";
import EmployeeEnum from '@/api/constant/employees'
import { getEmployeeList,delEmployee } from "@/api/employees";
import { formatDate } from "@/filters/index";

import QrCode from 'qrcode'     //生成二维码的插件包
export default {
  components: {
    AddEmployee,
    AssignRole
  },
  data () {
    return {
      list:[], //接收数组
      page:{
        page:1,    //页数
        size:10,   //每页条数
        total:0   //总数
      },
      loading: false,   //显示遮罩层
      showDialog: false,    //控制弹层显示
      showCodeDialog: false, //控制二维码弹层显示
      showRoleDialog: false,  //控制分配角色的弹层显示
      userId: null
    }
  },
  created () {
    this.getEmployeeList()  //调用获取员工列表的方法
  },
  methods: {
    async getEmployeeList(){
      this.loading = true
      const {total,rows} = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
      this.loading = false
    },
    changePage(newPage){
      this.page.page = newPage  //赋值最新的页码
      this.getEmployeeList() //重新拉取数据
    },
    // 格式化聘用数据
    formatEmployment(row, column, cellValue, index){
      const obj = EmployeeEnum.hireType.find(item => item.id === +cellValue)    //find会返回查找到的数组元素
      return obj ? obj.value : '未知'
    },
    // 删除员工
        // 删除员工
    async deleteEmployee(id) {
      try {
        await this.$confirm('您确定删除该员工吗')
        await delEmployee(id)       //调用删除角色的接口
        this.getEmployeeList()
        this.$message.success('删除员工成功')
      } catch (error) {
        console.log(error)
      }
    },
    // excel导出
    exportData(){
      // 表头对应关系
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 懒加载
      import('@/vendor/Export2Excel').then(async excel => {
                // excel是导出对象
                // rows是员工数据
        const { rows } = await getEmployeeList({page: 1,size: this.page.total})
        // 把数据格式和表头一一对应格式化
        const data = this.formatJson(headers,rows)
        // 复杂表头
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']   //合并单元格
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename:'员工工资表',
          multiHeader,
          merges
        })
      })
    },
    // 将表头数据和数据进行对应
    formatJson(headers,rows){
      return rows.map(item => {
        // item每个对象
        return Object.keys(headers).map(key =>{
          // 判断
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime'){
            return formatDate(item[headers[key]])
          }else if(headers[key] === 'formOfEmployment'){
            const obj = EmployeeEnum.hireType.find(item => item.id = headers[key])
            return obj ? obj.value : '未知'
          }
          return item[headers[key]]    
        })
      })
    },
    showQrCode(url){
      if(url){
        this.showCodeDialog = true
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas,url)   //将地址转换成二维码
        })  
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    // 点击角色按钮触发的方法
    async editRole(id){
      this.userId = id
      await this.$refs.assignRole.getUserDetailById(id)  //调用assign-role组件内的获取用户当前角色的方法
      // 弹出分配角色的弹层
      this.showRoleDialog = true
  
    }
  }
}
</script>

<style>

</style>
